<template>
  <a-drawer
    width="65%"
    placement="right"
    :visible="visible"
    :after-visible-change="afterVisibleChange"
    @close="onClose"
    title="角色设置"
  >
    <a-form-model
      :model="ruleForm"
      ref="ruleForm"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      class="form-card"
    >
      <a-form-model-item label="用户身份" prop="identityType">
        <a-radio-group v-model="ruleForm.identityType">
          <a-radio-button value="1"> 管理员 </a-radio-button>
          <a-radio-button value="2"> 资方 </a-radio-button>
          <a-radio-button value="3"> 标的公司 </a-radio-button>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="角色名称：" prop="roleName">
        <a-input v-model="ruleForm.roleName" placeholder="请输入" allow-clear></a-input>
      </a-form-model-item>
      <a-form-model-item label="角色描述：" prop="roleDesc">
        <a-input v-model="ruleForm.roleDesc" placeholder="请输入" allow-clear></a-input>
      </a-form-model-item>
      <a-form-model-item label="菜单权限：" prop="menuIds">
        <a-tree
          v-model="checkedKeys"
          checkable
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :selected-keys="selectedKeys"
          :tree-data="treeData"
          @expand="onExpand"
          @select="onSelect"
          :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
          @check="onCheck"
        />
      </a-form-model-item>
      <!-- <a-form-model-item label="状态：">
          <a-switch
            checked-children="启用"
            un-checked-children="停用"
            v-model="ruleForm.statusValue"
          />
        </a-form-model-item> -->
      <a-form-model-item :wrapper-col="{ span: 13, offset: 3 }">
        <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
        <a-button @click="onClose">取消</a-button>
      </a-form-model-item>
    </a-form-model>
  </a-drawer>
</template>

<script>
import { getRoleInfo, addRole, getRoleTree } from '@/api/system'
import CapitalSelect from '@/myComponents/capital-select.vue'
export default {
  name: 'RoleForm',
  data() {
    return {
      visible: false,
      ruleForm: {
        roleName: '',
        roleDesc: '',
        menuIds: [],
        identityType: '',
        capitalCode: undefined
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      rules: {
        identityType: [{ required: true, message: '用户身份不能为空' }],
        roleName: [{ required: true, message: '请输入角色名称' }],
        roleDesc: [{ required: true, message: '请输入角色描述' }],
        // capitalCode: [{ required: true, message: '请选择资方' }],
        menuIds: [{ required: true, message: '请选择菜单权限' }]
      },
      checkedKeys: {},
      selectedKeys: [],
      autoExpandParent: true,
      expandedKeys: [],
      treeData: [],
      submitLoading: false
    }
  },
  methods: {
    afterVisibleChange(val) {
      if (!val) {
        this.ruleForm = {
          roleName: '',
          roleDesc: '',
          menuIds: [],
          identityType: '',
          capitalCode: undefined
        }
      }
    },
    onClose() {
      this.visible = false
    },
    onSubmit() {
      const vm = this
      // this.ruleForm.status = this.ruleForm.statusValue ? '1' : '0'
      this.ruleForm.menuIds = this.checkedKeys.checked
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const formData = {
            ...this.ruleForm,
            menuIds: [
              ...new Set(this.checkedKeys.checked),
              ...new Set(this.checkedKeys.halfChecked)
            ]
          }
          formData.level3menuIds = [...new Set(this.checkedKeys.checked)]
          addRole(formData)
            .then((res) => {
              vm.$notification['success']({
                message: '提示',
                description: `${vm.ruleForm.id ? '编辑' : '新增'}成功`
              })
              vm.onClose()
              this.submitLoading = false
              vm.$emit('on-submit')
            })
            .catch(() => {
              this.submitLoading = false
            })
        }
      })
    },
    getRoleInfo(id) {
      getRoleInfo(id).then((res) => {
        console.log(res)
        res.data.statusValue = res.data.status == 1
        this.ruleForm = res.data
        this.checkedKeys = {
          checked: [...res.data.level3menuIds] || [],
          halfChecked: []
        }
      })
    },
    open(record = {}) {
      this.getRoleTree()
      if (record.id) {
        this.getRoleInfo(record.id)
      } else {
        this.checkedKeys = {
          checked: [],
          halfChecked: []
        }
      }
      this.visible = true
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    getRoleTree() {
      getRoleTree({
        channel: 'web'
      }).then((res) => {
        this.treeData = res.data
      })
    },
    onCheck(checkedKeys, e) {
      console.log(checkedKeys, e)
      this.checkedKeys.checked = checkedKeys
      this.checkedKeys.halfChecked = e.halfCheckedKeys

      // halfChecked
      // const list = this.backFather(e.node.eventKey, this.treeData, 'children', 'parentId')
      // const children = this.selectAllChild(e.node.eventKey, this.treeData)
      // if (e.checked) {
      //   // 选中添加：1.如果有父级，将各层父级都勾选；
      //   this.checkedKeys.checked.push(...list)
      //   // 去除重复id
      //   this.checkedKeys.checked = [...new Set(this.checkedKeys.checked)]
      //   // 2.如果有子集，将所有子集都勾选
      //   this.checkedKeys.checked.push(...children)
      // } else {
      //   // 1.去掉相关父级数字
      //   this.checkedKeys.checked = this.checkedKeys.checked.filter(
      //     (x) => !list.some((item) => x == item)
      //   )
      //   // 2.去掉子集数据
      //   this.checkedKeys.checked = this.checkedKeys.checked.filter(
      //     (x) => !children.some((item) => x == item)
      //   )
      // }
    },
    // 找到他的关联父级放到一个数组里
    backFather(id, tree, childName, parentId, end = 0) {
      var list = [id]
      // var that = this
      function backarr(childId, arr) {
        arr.forEach((item) => {
          if (item.id == childId) {
            // 找到指定的id了,进入寻找父级id
            if (item[parentId] == end) {
              // 到第一级了
              // list.unshift(0);
            } else {
              // 进入循环查找
              list.unshift(item[parentId])
              backarr(item[parentId], tree)
            }
          } else if (item[childName] && item[childName].length > 0) {
            backarr(childId, item[childName])
          }
        })
        return list
      }
      return backarr(id, tree)
    },
    // 找到所有子孙放到一个数组里面
    selectAllChild(ids, list) {
      const child = []
      // 查找指定id下所有子元素集合
      function nextChild(arr) {
        arr.forEach((item) => {
          if (item.children && item.children.length > 0) {
            child.push(...item.children.map((a) => a.id))
            nextChild(item.children)
          }
        })
      }
      // 找到指定id
      function findChild(ids, arr) {
        for (const item of arr) {
          if (item.id == ids) {
            if (item.children && item.children.length > 0) {
              child.push(...item.children.map((a) => a.id))
              nextChild(item.children)
              break
            }
          } else if (item.children && item.children.length > 0) {
            findChild(ids, item.children)
          }
        }
        return child
      }
      return findChild(ids, list)
    }
  },
  components: { CapitalSelect }
}
</script>

<style scoped>
.mb-none {
  margin-bottom: 0;
}
</style>
